package com.us.util.innerOpt;

import java.io.BufferedWriter;
import java.io.StringWriter;
import java.util.Locale;

import com.us.util.DateUtil;
import com.us.util.StringUtil;

import freemarker.cache.MruCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;

/********************************************************************************
 * <b>功能描述☞</b>Ftl的实现类<br>
 * <b>开发公司☞</b>重庆唯尼科技有限公司<br>
 * <b>版权☞</b>本文件归重庆唯尼科技有限公司所有<br>
 * <b>项目名☞</b>monlyu<br>
 * <b>文件路径☞</b>com.monlyu.bo.RoleBo.java<br>
 * <b>开发日期☞</b>2010-1-13 <br>
 * 
 * @author monlyu
 * @since JDK 5
 * @version : 1.0.7
 ********************************************************************************/
public class FtlRenderImpl implements FtlRender {

    private static Configuration config = null;

    /**
     * 获取本类的一个实例
     */
    public static FtlRenderImpl getInstance() {
        return new FtlRenderImpl();
    }

    /**
     * 默认构造器，用于初始化一些参数
     */
    public FtlRenderImpl() {
        if (config == null) {
            config = new Configuration();
            config.setDefaultEncoding("UTF-8");
            config.setEncoding(Locale.getDefault(), "UTF-8");
            config.setClassForTemplateLoading(getClass(), "/ftls");
            config.setDateFormat(DateUtil.DATETIME_PATTERN);
            config.setNumberFormat("#");
            config.setCacheStorage(new MruCacheStorage(20, 250));
        }
    }

    @Override
    public String render(Object model, String ftl) throws Exception {
        if (StringUtil.isEmpty(ftl)) {
            throw new IllegalArgumentException("参数Ftl文件名不能为空");
        }
        StringWriter stringWriter = new StringWriter();
        BufferedWriter writer = new BufferedWriter(stringWriter);
        Template template = config.getTemplate(ftl);
        template.setEncoding("UTF-8");
        template.process(model, writer);
        writer.flush();
        return stringWriter.toString();
    }

}
